<?php

/**
 * Impress - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Impress
 * @package Impress
 */

/**
 * This class provides access to data layer.
 *
 * @package Impress
 * @subpackage Models
 */

class ADS_DataFrameModel extends ADS_DefaultModel {
    
    public function countFrames() {
        return dibi::fetch('
          SELECT
            COUNT(*) as cnt
          FROM
            [:wp:ads_dataframes] AS t1
        ')->cnt;
    }
    
    public function getFrames() {
        return dibi::fetchAll('
          SELECT
            t1.frameId,
            t1.name,
            t1.htmlId
          FROM
            [:wp:ads_dataframes] AS t1
           %if', (bool)$this->useOrderBy, 'ORDER BY %by', $this->orderBy,
          '%if', (bool)$this->useLimit, '%lmt %ofs', $this->limit, $this->offset
        );
    }
    
    public function getFrame($frameId) {
        if(!is_int($frameId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.',__METHOD__));
        }
        return dibi::fetch('
          SELECT
            t1.frameId,
            t1.name,
            t1.htmlId
          FROM
            [:wp:ads_dataframes] AS t1
          WHERE
            frameId = %i
        ', $frameId);
    }    
    
    public function addFrame($frame){
        if(!is_array($frame)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }
        dibi::query('INSERT INTO [:wp:ads_dataframes]', $frame);
    }
    
    public function editFrame($frameId, $frame){
        if(!is_array($frame) || !is_int($frameId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }

        dibi::query('UPDATE [:wp:ads_dataframes] SET', $frame, 'WHERE frameId = %i', $frameId);
    }
    
    public function removeFrame($frameId){        
        if(!is_int($frameId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }

        dibi::query('DELETE FROM [:wp:ads_dataframe_items] WHERE frameId = %i', $frameId);
        dibi::query('DELETE FROM [:wp:ads_dataframes] WHERE frameId = %i LIMIT 1', $frameId);        
    }

}
